package com.guangfeng.yql.comm.netty.message;

import cn.hutool.extra.spring.SpringUtil;
import cn.hutool.json.JSONUtil;
import com.guangfeng.yql.comm.netty.annotation.ANettyMessage;
import com.guangfeng.yql.comm.netty.enumerate.NettyMessageType;
import com.guangfeng.yql.comm.netty.util.NettyAnnotationUtil;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;

import java.util.Map;
import java.util.TreeMap;

public class NettyMessageResolveFactory {

    private final static Map<NettyMessageType, NettyMessage> map = new TreeMap<>();

    static {
        Map<String, NettyMessage> NettyMessageMap = SpringUtil.getBeansOfType(NettyMessage.class);
        NettyMessageMap.forEach((key, value) -> {
            ANettyMessage annotation = NettyAnnotationUtil.getAnnotation(value, ANettyMessage.class);
            if (annotation != null) {
                map.put(annotation.value(), value);
            }
        });
    }

    public static NettyMessage getNettyMessage(TextWebSocketFrame text) {
        try {
            Map<String, Object> json = JSONUtil.parseObj(text.text());
            if (!json.containsKey("code")) {
                return null;
            }
            return map.get(NettyMessageType.getEnum(Integer.valueOf(json.get("code").toString())));
        } catch (RuntimeException e) {
            e.printStackTrace();
            return null;
        }

    }
}
